package com.it.nongchanping.controller;

import com.it.nongchanping.entity.News;
import com.it.nongchanping.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * 新闻控制器
 */
@Controller
@RequestMapping("/news")
public class NewsController {
    
    @Autowired
    private NewsService newsService;
    
    /**
     * 新闻列表页
     */
    @GetMapping("/list")
    public String newsList(@RequestParam(value = "type", required = false) String type, Model model) {
        try {
            List<News> newsList;
            if (type != null && !type.isEmpty()) {
                newsList = newsService.getNewsByType(type);
                model.addAttribute("currentType", type);
            } else {
                newsList = newsService.getPublishedNews();
            }
            
            // 确保newsList不为null
            if (newsList == null) {
                newsList = List.of();
            }
            
            model.addAttribute("newsList", newsList);
            
            // 新闻类型
            model.addAttribute("newsTypes", List.of("扶贫政策", "农产品文化故事", "助农活动新闻", "脱贫成效"));
            
            return "news/list";
        } catch (Exception e) {
            // 如果出现异常，返回空列表
            e.printStackTrace(); // 打印异常信息用于调试
            model.addAttribute("newsList", List.of());
            model.addAttribute("newsTypes", List.of("扶贫政策", "农产品文化故事", "助农活动新闻", "脱贫成效"));
            model.addAttribute("error", "暂时无法获取新闻数据，请稍后再试: " + e.getMessage());
            return "news/list";
        }
    }
    
    /**
     * 新闻详情页
     */
    @GetMapping("/detail/{id}")
    public String newsDetail(@PathVariable Long id, Model model) {
        News news = newsService.getNewsById(id);
        if (news == null) {
            return "redirect:/news/list";
        }
        
        // 增加浏览次数
        newsService.increaseViewCount(id);
        
        model.addAttribute("news", news);
        
        // 相关新闻
        List<News> relatedNews = newsService.getNewsByType(news.getType());
        relatedNews.removeIf(n -> n.getId().equals(id)); // 移除当前新闻
        model.addAttribute("relatedNews", relatedNews);
        
        return "news/detail";
    }
} 